package com.example.livemall.service.impl;

import com.example.livemall.dto.SearchResult;
import com.example.livemall.entity.Item;
import com.example.livemall.mapper.ImgsMapper;
import com.example.livemall.mapper.SearchMapper;
import com.example.livemall.service.SearchService;
import com.example.livemall.vo.SearchItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 搜索业务逻辑层
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private SearchMapper searchMapper;

    @Autowired
    private ImgsMapper imgsMapper;

    @Value("${origin}")
    private String origin;

    /**
     * 分页、高亮查询商品集合
     *
     * @param city
     * @param content
     * @param page
     * @param size
     * @return
     */
    @Override
    public SearchResult selectItemForPage(String city, String content, int page, int size) {
        // 设置高亮 <span style='color:red'></span>
        // page 从 0 开始
        if (page < 0) { return SearchResult.error(); }
        Integer offset = page * size;
        List<Item> items = searchMapper.selectItemForPage(city, content, content, content, offset, size);
        items = items.stream()
                .map(item -> item.setImgs(imgsMapper.selectImg(item.getId()))).collect(Collectors.toList());

        List<SearchItemVo> searchItemVos = items.stream()
                .map(item -> new SearchItemVo(
                        item.getId(),
                        item.getTitle(),
                        item.getImgs().get(0),
                        String.valueOf(item.getPrice()),
                        item.getRentType(),
                        item.getHouseType()))
                .collect(Collectors.toList());

        List<SearchItemVo> result = searchItemVos.stream()
                .peek(item -> {
                    item.setPrice("<h3>" + item.getPrice() + "</h3>");
                    item.setImg(origin + searchMapper.selectImg(item.getId(), "search"));
                })
                .collect(Collectors.toList());

        Integer total = searchMapper.selectItemForPageTotal(city, content, content, content);
        Boolean hasMore = (total - offset - items.size()) > 0;
        return SearchResult.success(hasMore, result);
    }

}
